import { AsyncLocalStorage } from 'async_hooks';

export interface RequestContext {
    traceId: string;
    uri: string;
    timestamp: string;
}

// 创建 AsyncLocalStorage 实例
export const asyncLocalStorage = new AsyncLocalStorage<RequestContext>();

/**
 * 设置请求上下文
 */
export function setRequestContext(context: RequestContext): void {
    asyncLocalStorage.enterWith(context);
}

/**
 * 获取当前请求上下文
 */
export function getCurrentContext(): RequestContext | undefined {
    return asyncLocalStorage.getStore();
}

/**
 * 获取 traceId
 */
export function getCurrentTraceId(): string {
    const context = getCurrentContext();
    return context?.traceId || 'unknown';
}

/**
 * 获取 URI
 */
export function getCurrentUri(): string {
    const context = getCurrentContext();
    return context?.uri || 'unknown';
}

/**
 * 获取完整上下文
 */
export function getCurrentFullContext(): RequestContext {
    const context = getCurrentContext();
    return (
        context || {
            traceId: 'unknown',
            uri: 'unknown',
            timestamp: new Date().toISOString(),
        }
    );
}
